<?php

namespace app\admin\controller;

use app\BaseController;
use app\model\RatingScaleModel;
use app\model\RatingScalePackInfoModel;
use app\model\RatingScalePackModel;
use app\model\TaskRatingScaleModel;
use think\App;

class RatingScalePack extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new RatingScalePackInfoModel();
    }

    /**
     * 量表包列表
     * @return false|string
     */
    public function list(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%'.$param['name'].'%'];
            }
            if (!empty($param['rating_scale_name'])) {
//                $where[] = ['rating_scale_name', 'like', '%'.$param['rating_scale_name'].'%'];
                $RatingScaleModel = new RatingScaleModel();
                $rating_scale_id = $RatingScaleModel->where([
                    ['name', 'like', '%'.$param['rating_scale_name'].'%'],
                    ['unit_id','=',$this->userData['unit_id']]
                ])->column('id');
                if (count($rating_scale_id)){
                    $RatingScalePackModel = new RatingScalePackModel();
                    $pack_info_id = $RatingScalePackModel->where([
                        ['rating_scale_id', 'in', $rating_scale_id],
                    ])->column('pack_info_id');
                    if (count($pack_info_id)){
                        $where[] = ['id', 'in', $pack_info_id];
                    }
                }else{
                    $where[] = ['id', '=', -1];
                }
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->with([
                'RatingScalePack' => function($query) {
                    $query->with(['RatingScale']);
                }
            ])->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['num'] = count($item['RatingScalePack']);
                $rating_scale_name = array_column($item['RatingScalePack'], 'rating_scale_name');
                $item['rating_scale_name'] = implode('、', $rating_scale_name);
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 新增量表包
     * @return false|string
     */
    public function add(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->mode->startTrans();
            if (!empty($param['name'])){
                if ($this->mode->where([
                    ['name','=',$param['name']],
                    ['unit_id','=',$this->userData['unit_id']]
                ])->value('id')) {
                    throw new \Exception('量表包名称不可重复！');
                }
            }
            if (!empty($param['pack'])) {
                $pack = $param['pack'];
                unset($param['pack']);
                $rating_scale_id = array_column($pack, 'rating_scale_id');
                if (count($rating_scale_id) != count(array_unique($rating_scale_id))) throw new \Exception('量表不可重复！');
            }else{
                throw new \Exception('请选择子量表');
            }
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            $infoId = $this->mode->insertGetId($param);
            $packData = [];
            foreach ($pack as $item) {
                $packData[] = [
                    'pack_info_id' => $infoId,
                    'rating_scale_id' => $item['rating_scale_id'],
                    'time'  => time()
                ];
            }
            $RatingScalePackModel = new RatingScalePackModel();
            $RatingScalePackModel->insertAll($packData);
            $this->mode->commit();
            return success([],'添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 更新量表包
     * @return false|string
     */
    public function update(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->mode->startTrans();
            $info = $this->mode->find($param['id']);
            if (!empty($param['name']) && $info['name'] != $param['name']){
                if ($this->mode->where([
                    ['name','=',$param['name']],
                    ['unit_id','=',$this->userData['unit_id']]
                ])->value('id')) {
                    throw new \Exception('量表包名称不可重复！');
                }
            }
            if (!empty($param['pack'])) {
                $pack = $param['pack'];
                unset($param['pack']);
                $rating_scale_id = array_column($pack, 'rating_scale_id');
                if (count($rating_scale_id) != count(array_unique($rating_scale_id))) throw new \Exception('量表不可重复！');
            }else{
                throw new \Exception('请选择子量表');
            }
            $param['unit_id'] = $this->userData['unit_id'];
            $param['time'] = time();
            $info->save($param);
            $packData = [];
            foreach ($pack as $item) {
                $packData[] = [
                    'pack_info_id' => $param['id'],
                    'rating_scale_id' => $item['rating_scale_id'],
                    'time'  => time()
                ];
            }
            $RatingScalePackModel = new RatingScalePackModel();
            $RatingScalePackModel->where('pack_info_id','=',$param['id'])->update([
                'is_del' => 1,
                'del_time'  => time()
            ]);
            $RatingScalePackModel->insertAll($packData);
            $this->mode->commit();
            return success([],'添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除量表包
     * @return false|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            if (is_array($id)){
                $is_task = $TaskRatingScaleModel->where('pack_id','in',$id)->value('id');
                if ($is_task) throw new \Exception('有任务正在使用该量表包无法删除！');
                $this->mode->where('id','in',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $is_task = $TaskRatingScaleModel->where('pack_id','=',$id)->value('id');
                if ($is_task) throw new \Exception('有任务正在使用该量表包无法删除！');
                $this->mode->where('id','=',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }

            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 修改量表包状态
     * @return false|string
     */
    public function status(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status');
            $this->mode->where('id','=',$id)->update([
                'status' => $status
            ]);
            return success([],'修改成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表包基本信息
     * @return false|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $info = $this->mode->find($id);
            if (!$info) throw new \Exception('参数错误!');
            $RatingScalePackModel = new RatingScalePackModel();
            $rating_scale_ids = $RatingScalePackModel->where('pack_info_id','=',$id)->column('rating_scale_id');
            $RatingScaleModel = new RatingScaleModel();
            $RatingScaleList = $RatingScaleModel->field('id,name,type_id')
                ->where('id','in',$rating_scale_ids)
                ->with(['ratingScaleTypeName'])
                ->select()->toArray();
            $RatingScaleData = [];
            foreach ($RatingScaleList as $item) {
                $RatingScaleData[] = [
                    'rating_scale_id' => $item['id'],
                    'rating_scale_name' => $item['name'],
                    'type_id' => $item['type_id'],
                    'rating_scale_type_name' => $item['rating_scale_type_name'],
                ];
            }
            $info['pack'] = $RatingScaleData;
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


}
